import cv2
import mediapipe
import time

cap = cv2.VideoCapture(0)
time1 = time.time()

#初始化库
facedetection = mediapipe.solutions.face_detection.FaceDetection(min_detection_confidence=0.7)
draw = mediapipe.solutions.drawing_utils

while True:
    success , img =cap.read()
    imgRGB = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)

    #打印坐标信息
    result = facedetection.process(imgRGB)
    bbox_list =[]
    if result.detections:
        for id,detection in enumerate(result.detections):

            #打印信息
            # print(x,detection)

            #画边框1 自带的api
            #raw.draw_detection(img,detection)

            #画边框2
            bounding_box = detection.location_data.relative_bounding_box
            #print(bounding_box)
            H,W,_ = img.shape
            x,y,w,h = int(bounding_box.xmin * W), int(bounding_box.ymin*H), int(bounding_box.width*W), int(bounding_box.height*H)
            cv2.rectangle(img,(x,y),(x+w,y+h),(255,255,0),2)

            cv2.putText(img, f'confidence: {int(detection.score[0] * 100)}%', (x, y), cv2.FONT_HERSHEY_PLAIN, 2,
                        (255, 255, 0), 2)

    #设定帧数
    time2 = time.time()
    fps = 1/(time2-time1)
    time1 = time2
    cv2.putText(img,f'FPS:{int(fps)}',(20,50),cv2.FONT_HERSHEY_SIMPLEX,0.8,(0,0,255),2)

    cv2.imshow("output", img)
    if cv2.waitKey(1) & 0xFF == 27:
        break